import requests
import threading
from typing import Dict, Any, Optional, Union


class ThreadHTTPClient:
    def __init__(self, base_url: str = "", headers: Dict[str, str] = None, timeout: int = 30):
        self.base_url = base_url.rstrip('/')
        self.default_headers = headers or {}
        self.timeout = timeout

        # 使用线程本地存储来隔离每个线程的session
        self._thread_local = threading.local()

    @property
    def session(self) -> requests.Session:
        """为每个线程创建独立的session"""
        if not hasattr(self._thread_local, 'session'):
            self._thread_local.session = requests.Session()
            # 设置默认headers
            if self.default_headers:
                self._thread_local.session.headers.update(self.default_headers)
        return self._thread_local.session

    def _build_url(self, endpoint: str) -> str:
        """构建完整的URL"""
        endpoint = endpoint.lstrip('/')
        return f"{self.base_url}/{endpoint}" if self.base_url else endpoint

    def get(self, endpoint: str = "", params: Dict[str, Any] = None, **kwargs) -> requests.Response:
        """发送GET请求"""
        url = self._build_url(endpoint)
        return self.session.get(url, params=params, timeout=self.timeout, **kwargs)

    def post(self, endpoint: str = "", data: Dict[str, Any] = None,
             json: Dict[str, Any] = None, params: Dict[str, Any] = None, **kwargs) -> requests.Response:
        """发送POST请求"""
        url = self._build_url(endpoint)
        return self.session.post(url, data=data, json=json, params=params, timeout=self.timeout, **kwargs)

    def delete(self, endpoint: str = "", **kwargs) -> requests.Response:
        """发送DELETE请求"""
        url = self._build_url(endpoint)
        return self.session.delete(url, timeout=self.timeout, **kwargs)

    def patch(self, endpoint: str = "", data: Dict[str, Any] = None,
              json: Dict[str, Any] = None, **kwargs) -> requests.Response:
        """发送PATCH请求"""
        url = self._build_url(endpoint)
        return self.session.patch(url, data=data, json=json, timeout=self.timeout, **kwargs)

    def put(self, endpoint: str = "", data: Dict[str, Any] = None,
            json: Dict[str, Any] = None, **kwargs) -> requests.Response:
        """发送PUT请求"""
        url = self._build_url(endpoint)
        return self.session.put(url, data=data, json=json, timeout=self.timeout, **kwargs)

    def close(self):
        """关闭当前线程的session"""
        if hasattr(self._thread_local, 'session'):
            self._thread_local.session.close()

    def update_headers(self, headers: Dict[str, str]):
        """更新默认headers"""
        self.default_headers.update(headers)
        if hasattr(self._thread_local, 'session'):
            self._thread_local.session.headers.update(headers)